﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data.SqlClient;
using System.Configuration;

namespace CarServiseSite
{
    public partial class AutorizationForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string uid = "";
            string login = "";
            string type = "";
            bool haveCookie = ReadCoolies(out uid, out login, out type);

            if (haveCookie && (type == "Admin" || type == "Manager" || type == "Worker" || type == "Client"))
            {
                string procStr = "";

                if (type == "Admin")
                    procStr = "ReadUidAdmin";
                else if (type == "Manager")
                    procStr = "ReadUidManager";
                else if (type == "Worker")
                    procStr = "ReadUidWorker";
                else if (type == "Client")
                    procStr = "ReadUidClient";

                ConnectionStringSettings css =
                    ConfigurationManager.ConnectionStrings["CarServiceConnectionString"];
                string ss = css.ConnectionString;

                SqlConnection conn = new SqlConnection(ss);
                conn.Open();
                SqlCommand cmd = new SqlCommand(procStr, conn);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Login", login);
                cmd.Parameters.AddWithValue("@UID", uid);

                SqlDataReader r = cmd.ExecuteReader();
                r.Read();
                bool b = r.HasRows;

                if (b)
                    Redirect(type);
                
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string type = DropDownList1.SelectedValue;
            string login = TextBox1.Text;
            string password = TextBox2.Text;

            ConnectionStringSettings css =
                ConfigurationManager.ConnectionStrings["CarServiceConnectionString"];
            string ss = css.ConnectionString;

            string getprocedure = "";
            string SessType = "";
            string setQuckieProc = "";

            if (type == "Клиент")
            {
                getprocedure = "GetClientByLoginPassword";
                SessType = "Client";
                setQuckieProc = "SetUIDClient";
            }
            else if (type == "Рабочий")
            {
                getprocedure = "GetWorkerByLoginPassword";
                SessType = "Worker";
                setQuckieProc = "SetUIDWorker";
            }
            else if (type == "Менеджер")
            {
                getprocedure = "GetManagerByLoginPassword";
                SessType = "Manager";
                setQuckieProc = "SetUIDManager";
            }
            else if (type == "Администратор")
            {
                getprocedure = "GetAdminByLoginPassword";
                SessType = "Admin";
                setQuckieProc = "SetUIDAdmin";
            }

            if (getprocedure == "" || SessType == "" || setQuckieProc == "")
            {
            }
            else
                try
                {

                    SqlConnection conn = new SqlConnection(ss);
                    conn.Open();
                    SqlCommand cmd = new SqlCommand(getprocedure, conn);
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Login", TextBox1.Text);
                    cmd.Parameters.AddWithValue("@Password", TextBox2.Text);

                    SqlDataReader r = cmd.ExecuteReader();
                    r.Read();
                    bool b = r.HasRows;

                    conn.Close();

                    if (b)
                    {
                        Session["Login"] = TextBox1.Text;
                        Session["Type"] = SessType;

                        //if remember me
                        if (CheckBox1.Checked)
                        {
                            Random rand = new Random();
                            int UIDint = rand.Next(0, 1000000000);

                            //write cookie
                            WriteCookie(UIDint.ToString(), TextBox1.Text, SessType);

                            //write database
                            conn = new SqlConnection(ss);
                            conn.Open();
                            cmd = new SqlCommand(setQuckieProc, conn);
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@Login", TextBox1.Text);
                            cmd.Parameters.AddWithValue("@Password", TextBox2.Text);
                            cmd.Parameters.AddWithValue("@UID", UIDint.ToString());
                            cmd.ExecuteNonQuery();

                            conn.Close();
                        }

                        Redirect(SessType);
                    }

                }
                catch (Exception ex )
                {
                    ErrorLabel.Text = "Непредвиденная ошибка";
                }
        }

        bool ReadCoolies(out string uid, out string login, out string type)
        {
            string uidS = "";
            string loginS = "";
            string typeS = "";

            if (Request.Cookies["UID"] != null)
                uidS = Request.Cookies["UID"].Value;
            if (Request.Cookies["Login"] != null)
                loginS = Request.Cookies["Login"].Value;
            if (Request.Cookies["Type"] != null)
                typeS = Request.Cookies["Type"].Value;

            uid = uidS;
            login = loginS;
            type = typeS;

            if (uidS == "" || loginS == "" || typeS == "")
                return false;
            else
                return true;
        }

        void Redirect(string type)
        {
            if (type == "Admin")
                Response.Redirect("~/Admins_Admin.aspx");
            else if (type == "Manager")
                Response.Redirect("~/CheapestOpeartion_Manager.aspx");
            else if (type == "Worker")
                Response.Redirect("~/UserDuscount_Manager_Worker.aspx");
            else if (type == "Client")
                Response.Redirect("~/MenuClient.aspx");
        }

        void WriteCookie(string uidS, string loginS, string typeS)
        {
            HttpCookie uid = new HttpCookie("UID");
            uid.Value = uidS;
            uid.Expires = DateTime.Now.AddYears(1);
            Response.Cookies.Add(uid);

            HttpCookie loginC = new HttpCookie("Login");
            loginC.Value = loginS;
            loginC.Expires = DateTime.Now.AddYears(1);
            Response.Cookies.Add(loginC);

            HttpCookie typeC = new HttpCookie("Type");
            typeC.Value = typeS;
            typeC.Expires = DateTime.Now.AddYears(1);
            Response.Cookies.Add(typeC);   
        }
    }
}